package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.product.client.common.result.Result;
import com.atguigu.gmall.product.client.common.util.AuthContextHolder;
import com.atguigu.gmall.product.client.model.cart.CartInfo;
import com.atguigu.gmall.product.client.model.order.OrderDetail;
import com.atguigu.gmall.product.client.model.order.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

//订单微服务  去结算  提交订单

@RestController
@RequestMapping("/api/order")
public class OrderApiController {


    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;
    //查询商品清单
    //交易号
    //已经写在了用户微服务中了  本次就不写用户收货地址
    @GetMapping("/trade")
    public Map<String,Object> trade(HttpServletRequest request){
        Map<String, Object> result = null;
        //1:查询商品清单
        List<CartInfo> cartListChecked = cartFeignClient.getCartListChecked();
        if(!CollectionUtils.isEmpty(cartListChecked)){
            result = new HashMap<>();

            List<OrderDetail> orderDetailList = cartListChecked.stream().map(cartInfo -> {
                OrderDetail detail = new OrderDetail();
                detail.setImgUrl(cartInfo.getImgUrl());
                detail.setSkuName(cartInfo.getSkuName());
                detail.setOrderPrice(cartInfo.getSkuPrice());
                detail.setSkuNum(cartInfo.getSkuNum());
                detail.setSkuId(cartInfo.getSkuId());
                return detail;
            }).collect(Collectors.toList());
            result.put("detailArrayList",orderDetailList);
            //2:总件数
            long totalNum = orderDetailList.stream().collect(
                    Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
            result.put("totalNum",totalNum);

            //3:总金额
            BigDecimal totalAmount = new BigDecimal("0");
            for (OrderDetail orderDetail : orderDetailList) {
                BigDecimal orderPrice = orderDetail.getOrderPrice();
                totalAmount = totalAmount.add(orderPrice.multiply(new BigDecimal(orderDetail.getSkuNum())));
            }
            result.put("totalAmount",totalAmount);

            //4:交易号
            String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
            String userId = AuthContextHolder.getUserId(request);
            redisTemplate.opsForValue().set("tradeNo:" + userId,tradeNo);
            result.put("tradeNo",tradeNo);
        }
        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result  submitOrder(@RequestBody OrderInfo orderInfo,String tradeNo,HttpServletRequest request){
        //1. 判断订单号是否正确  防止二次提交 幂等性问题
        String userId = AuthContextHolder.getUserId(request);
        //如果订单号是没有的话  就是修改了浏览器上的页面   是非法操作
        if (StringUtils.isEmpty(tradeNo)){
            return Result.fail().message("非法操作");
        }
        Object o = redisTemplate.opsForValue().get("tradeNo:" + userId);
        //如果没有值  就是已经提交过了
        if (o == null){
            return Result.fail().message("请勿重复提交订单");
        }else if (!tradeNo.equals(o)){   //如果订单号不一样的话  就是证明在前端页面上被人修改了  是非法操作
            return Result.fail().message("非法操作");
        }
        //交易订单号正确
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)) {
            for (OrderDetail orderDetail : orderDetailList) {
                //校验库存
                boolean flag = orderInfoService.
                        hasStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                if (!flag) {
                    return Result.fail().message(orderDetail.getSkuName() + "[此商品已经售完]");
                }
            }
        }

        //3. 保存订单主表  订单详情表
        orderInfo.setUserId(Long.parseLong(userId));  //用户Id
         Long orderId = orderInfoService.submitOrder(orderInfo);
         return Result.ok(orderId);
        }

        //根据订单Id 查询订单对象
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable  Long orderId){

        return orderInfoService.getOrderInfo(orderId);
    }

    @PostMapping("/orderSpilt")
    public String orderSplit(Long orderId,String wareSkuMap){

        // 查询仓库系统 拆单接口说明
        //1. 开始拆单
/*        List<OrderInfo> orderInfoList =orderInfoService.orderSplit(orderId,wareSkuMap);
        //2. 拆单后的集合
        List<Map> listMap = orderInfoList.stream().map(orderInfo -> {
            return orderInfoService.initWareOrder(orderInfo);
        }).collect(Collectors.toList());*/

        List<Map> listMap = orderInfoService.orderSplit1(orderId,wareSkuMap);
        //转成字符串
        return JSONObject.toJSONString(listMap);
    }
}
